package com.example.once.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.once.common.Result;
import com.example.once.entity.Goods;
import com.example.once.mapper.GoodsMapper;
import com.example.once.common.PageQuery;
import com.example.once.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xinTong
 * @since 2023-12-16
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 增
     * @param goods
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody Goods goods){
        return goodsService.save(goods) ? Result.suc() : Result.fail();
    }

    /**
     * 删
     * @param id
     * @return
     */
    @GetMapping("/delete")
    public Result delete(@RequestParam Integer id){
        return goodsService.removeById(id) ? Result.suc() : Result.fail();
    }

    /**
     * 改
     * @param goods
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody Goods goods){
        return goodsService.updateById(goods) ? Result.suc() : Result.fail();
    }

    /**
     * 查
     * @param query
     * @return
     */
    @PostMapping("/select")
    public Result select(@RequestBody PageQuery query) {
        HashMap param = query.getParam();
        String name = (String) param.get("name");

        IPage<Goods> page = new Page<>(query.getPageNum(), query.getPageSize());


        LambdaQueryWrapper<Goods> goodsLambdaQueryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(name)) {
            goodsLambdaQueryWrapper.like(Goods::getName, name);
        }

        IPage<Goods> iPage = goodsMapper.selectPage(page, goodsLambdaQueryWrapper);
        System.out.println("总页数： " + page.getPages());
        System.out.println("总记录数： " + page.getTotal());

        return Result.suc(iPage.getRecords(), iPage.getTotal());
    }
}
